package com.proton.carepatchtemp.fragment;


import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.SystemClock;
import android.os.Vibrator;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.activity.DeviceShareActivity;
import com.proton.carepatchtemp.activity.MainActivity;
import com.proton.carepatchtemp.activity.NotesListActivity;
import com.proton.carepatchtemp.activity.RealTimeChartActivity;
import com.proton.carepatchtemp.activity.ReportDetailActivity;
import com.proton.carepatchtemp.application.VCare;
import com.proton.carepatchtemp.base.BaseFragment;
import com.proton.carepatchtemp.constant.Codes;
import com.proton.carepatchtemp.constant.Config;
import com.proton.carepatchtemp.constant.Extras;
import com.proton.carepatchtemp.constant.NtfID;
import com.proton.carepatchtemp.constant.Settings;
import com.proton.carepatchtemp.constant.XTypes;
import com.proton.carepatchtemp.database.RealData;
import com.proton.carepatchtemp.database.TestManager;
import com.proton.carepatchtemp.database.XmppMsg;
import com.proton.carepatchtemp.database.table.Device;
import com.proton.carepatchtemp.database.table.Profile;
import com.proton.carepatchtemp.database.table.Report;
import com.proton.carepatchtemp.database.table.ShareHistory;
import com.proton.carepatchtemp.fragment.dialogfragment.TestNoticeFragment;
import com.proton.carepatchtemp.ui.MyCountDownTimer;
import com.proton.carepatchtemp.utils.FormatUtils;
import com.proton.carepatchtemp.utils.Ntf.NotificationUtils;
import com.proton.carepatchtemp.utils.NumUtils;
import com.proton.carepatchtemp.utils.SpUtils;
import com.proton.carepatchtemp.utils.TastyUtils;
import com.proton.carepatchtemp.utils.ThreadUtils;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.proton.carepatchtemp.utils.net.DeviceCenter;
import com.proton.carepatchtemp.utils.net.MsgCenter;
import com.proton.carepatchtemp.utils.net.PrfCenter;
import com.proton.carepatchtemp.utils.net.XMPPCenter;
import com.proton.carepatchtemp.utils.ui.ToastUtils;
import com.sdsmdg.tastytoast.TastyToast;
import com.sinping.iosdialog.dialog.widget.ActionSheetDialog;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;
import java.util.Objects;

import cn.pedant.SweetAlert.SweetAlertDialog;
import cn.pedant.SweetAlert.Type;
import cn.qqtheme.framework.picker.NumberPicker;

import static android.content.Context.NOTIFICATION_SERVICE;
import static com.proton.carepatchtemp.constant.NtfID.DEVICE_DISCONNECTED;
import static com.proton.carepatchtemp.constant.NtfID.LOW_OR_HIGH_WARNING;
import static com.proton.carepatchtemp.fragment.ShareReportFragment.bmpToByteArray;
import static com.proton.carepatchtemp.utils.SpUtils.getBoolean;

public class RealTimeItemFragment extends BaseFragment {

    public static final int DEVICE_SHARE = 1003;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    //是否为分享界面
    public boolean isShare = false;
    // TODO: Rename and change types of parameters
    public String tag = "";
    public int isDelete = 0; //2为停止测量，1位删除整个页面
    //高温报警温度
    protected float highWarning = 37.5F;
    //低温报警温度
    protected float lowWarning = 35.0F;
    DecimalFormat mFormat;
    private IWXAPI api;
    //连接状态
    private boolean isConnected = false;
    //  第一次超过36.0后可以报警
    private boolean isFirstHigh = false;
    //  低电量提醒标志
    private boolean isNtfPower = false;
    //高温报警标志位
    private boolean CanHighNtf = true;
    //低温报警标志位
    private boolean CanLowNtf = true;
    //高温报警延时
    private long highNtfTime = 0L;
    //低温报警延时
    private long lowNtfTime = 0L;
    private long timeOut = 0;
    //  msg数量
    private long msgCount = 0;
    private UpdataTempTimer mUpdataTempTimer;
    //  温度单位标志 1 = 摄氏度； 2 = 华氏度
    private int tempUnit = 0;
    private NumberPicker mHighTempPicker;
    private NumberPicker mLowTempPicker;
    private ImageView mIvDelete;
    private SimpleDraweeView mSdvProfileAvatar;
    /**
     * ---
     */
    private TextView mTvProfileName;
    /**
     * 36.20
     */
    private TextView mTvRealTimeTemp;
    /**
     * ℃
     */
    private TextView mTvTempUnit;
    /**
     * 36.02
     */
    private TextView mTvRealtimeHighestTemp;
    /**
     * ℃
     */
    private TextView mTvTempUnit1;
    /**
     * 16小时37分
     */
    private TextView mTvSumTestTime;
    /**
     * 36.5℃
     */
    private TextView mTvSettingWarningLow;
    /**
     * 36.5℃
     */
    private TextView mTvSettingWarningHigh;
    private FloatingActionButton mFabRealChart;
    private FloatingActionButton mFabStopTest;
    private FloatingActionButton mFabShare;
    /**
     * 设备id
     */
    private TextView mTvDeviceId;
    private Typeface mFace;
    private RelativeLayout mRtlRealTimeTemp;
    private FloatingActionButton mFabReconnect;
    private ImageView mIvPower;
    private TextView mTvPowerValue;
    private LinearLayout mLnlRangeNotice;
    private ImageView mIvShowNotice;
    private ProgressDialog mProgressDialog;
    private AlertDialog.Builder mADBuilder;
    /**
     * (25℃~45℃)
     */
    private TextView mTvTempRange;
    /**
     * 已断开
     */
    private TextView mTvBluetoothState;
    private ImageView mIvAddNote;
    private boolean isHightNtfShow = false;
    private boolean isDisconnectWarm;

    public RealTimeItemFragment() {
    }

    public static RealTimeItemFragment newInstance(String tag, RealData info) {
        RealTimeItemFragment fragment = new RealTimeItemFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, tag);
        args.putSerializable(ARG_PARAM2, info);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void dealEvent(MainEvent event) {
        switch (event.getId()) {
            case Codes.DEVICE_FIRST_CONNECT:
                if (event.getKey().equalsIgnoreCase(tag)) {
                    mProgressDialog.setMessage(getString(R.string.string_cache_reading));
                    mProgressDialog.show();
                    LogUtils.d("DEVICE_FIRST_CONNECT  缓存读取中");
                }
                break;
            case Codes.DEVICE_LOADED_CACHE:
                if (event.getKey().equalsIgnoreCase(tag)) {
                    //  缓存读取完成后清除弹窗
                    mProgressDialog.dismiss();
                    if (!mUpdataTempTimer.isRunning()) {
                        mUpdataTempTimer.start();
                    }
                    LogUtils.d("DEVICE_LOADED_CACHE  缓存读取完成！");
                }
                break;

            case Codes.TEST_CACHE_TIMEOUT:
                if (event.getKey().equalsIgnoreCase(tag)) {
                    mProgressDialog.dismiss();
                    TastyUtils.makeTextShort(R.string.string_read_cache_timeout, TastyToast.DEFAULT);
                }
                break;

            //  连接失败
            case Codes.BT_CONNECT_FAILED:
                LogUtils.d("Device connect failed ! received!");
                if (event.getKey().equalsIgnoreCase(tag)) {
//                    TastyUtils.makeTextShort("设备连接失败！请检查设备是否正常！", TastyToast.ERROR);
                    LogUtils.d("Device connect failed ! received!    " + tag);
                    mFabReconnect.setVisibility(View.VISIBLE);
                    mFabStopTest.setVisibility(View.INVISIBLE);
                    mFabRealChart.setEnabled(false);
                    mFabShare.setEnabled(false);
//                    mLnlFabMenu.setVisibility(View.GONE);
                    mProgressDialog.dismiss();
                }
                mProgressDialog.dismiss();
                break;
            //  连接成功
            case Codes.DEVICE_STATE_CONNECTED:
                LogUtils.d("Timeout = " + timeOut);
                if (event.getKey().equalsIgnoreCase(tag)) {
                    if (!mUpdataTempTimer.isRunning()) {
                        mUpdataTempTimer.start();
                    }
                    mFabReconnect.setVisibility(View.INVISIBLE);
                    mFabStopTest.setVisibility(View.VISIBLE);
                    mFabShare.setEnabled(false);
                    mFabRealChart.setEnabled(false);
//                    mLnlFabMenu.setVisibility(View.VISIBLE);
                    isConnected = true;
                    mTvBluetoothState.setText(R.string.string_connected);
                    mTvBluetoothState.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getContext(), R.mipmap.bluetooth_connected), null, null, null);
                }
                mProgressDialog.dismiss();
                break;

            //连接中
            case Codes.DEVICE_STATE_CONNECTING:
                if (event.getKey().equalsIgnoreCase(tag)) {
                    mTvBluetoothState.setText(R.string.string_connecting);
                    mTvBluetoothState.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getContext(), R.mipmap.bluetooth_connecting), null, null, null);
                }
                break;

            //  断开连接
            case Codes.DEVICE_STATE_DISCONNECTED:
                mProgressDialog.dismiss();
                if (event.getKey().equalsIgnoreCase(tag)) {
                    isConnected = false;
                    mTvBluetoothState.setText(R.string.string_disconnect);
                    mTvBluetoothState.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getContext(), R.mipmap.bluetooth_connecting), null, null, null);

                    mFabReconnect.setVisibility(View.VISIBLE);
                    mFabStopTest.setVisibility(View.INVISIBLE);
                    mFabShare.setEnabled(false);
                    mFabRealChart.setEnabled(false);

                    mTvRealTimeTemp.setText("--.--");
                    mTvRealtimeHighestTemp.setText("--.--");
                    mTvSumTestTime.setText(R.string.string_h_m);
                }
                break;

            case Codes.BT_DEVICE_POWER_VALUE:
                if (event.getKey().equalsIgnoreCase(tag)) {
                    isConnected = true;
                    mTvBluetoothState.setText(R.string.string_connected);
                    mTvBluetoothState.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getContext(), R.mipmap.bluetooth_connected), null, null, null);
                    updataPower((Integer) event.getObj());
                }
                break;
            case Codes.BT_ADD_DEVICE_CONNECT:
                if (event.getKey().equalsIgnoreCase(tag)) {
                    mFabReconnect.setVisibility(View.INVISIBLE);
                    mFabStopTest.setVisibility(View.VISIBLE);
                    mFabShare.setEnabled(true);
                    mFabRealChart.setEnabled(true);
                }
                break;
            case Codes.SETTING_TEMP_UNIT_C:
                tempUnit = 1;
                mTvTempUnit.setText("℃");
                mTvTempUnit1.setText("℃");
                mTvTempRange.setText("(25℃~45℃)");
                break;
            case Codes.SETTING_TEMP_UNIT_F:
                tempUnit = 2;
                mTvTempUnit.setText("℉");
                mTvTempUnit1.setText("℉");
                mTvTempRange.setText("(77℉~113℉)");
                break;
            case Codes.ADD_DEVICE:
                if (event.getMsg().equalsIgnoreCase(tag)) {
                    if (event.getObj() == null) {
                        TastyUtils.makeText(getString(R.string.string_create_report_fail) + event.getMsg(), TastyToast.LENGTH_LONG, TastyToast.ERROR);
                        break;
                    }
                    LogUtils.d("ADD_DEVICE is Success");
                    Device dvc = (Device) event.getObj();
                    TestManager.setDevice(dvc.getBtaddress(), dvc);
                } else if (!event.isSuccess()) {
                    TastyUtils.makeText(getString(R.string.string_get_report_id_fail) + event.getMsg(), TastyToast.LENGTH_LONG, TastyToast.ERROR);
                }
                break;
            //取消设备分享
            case Codes.DEVICE_CANCLE_SHARE:
                if (Long.parseLong(event.getKey()) == (TestManager.getProfileID(tag))) {
                    long shareId = (long) event.getObj();
                    for (ShareHistory.SharelistBean ssb :
                            TestManager.getShareList(tag)) {
                        if (shareId == ssb.getId()) {
                            if (ssb.isCanSend()) {
                                LogUtils.e(ssb);
                                sendUNShareMsg(ssb.getUid());
                            }
                            TestManager.getShareList(tag).remove(ssb);
                            return;
                        }
                    }
                }
                break;
            //设备分享记录
            case Codes.DEVICE_SHARE_HISTORY:
                if (event.getKey().equalsIgnoreCase(tag)) {
                    LogUtils.d(event);
                    if (null == event.getObj()) {
                        return;
                    }

                    ShareHistory tempHistory = (ShareHistory) event.getObj();
                    TestManager.setShareList(tempHistory.getBtaddress(), tempHistory.getSharelist());
                }
                break;
            //添加报告
            case Codes.NET_ADD_REPORT:
                if (event.getKey().equalsIgnoreCase(tag)) {
                    TestManager.get(tag).isGetRptID = true;
                    DeviceCenter.getShareHistory(String.valueOf(TestManager.getDeviceID(tag)));
                } else if (!event.isSuccess()) {
                    TastyUtils.makeText(getString(R.string.string_get_report_id_fail) + event.getMsg(), TastyToast.LENGTH_LONG, TastyToast.ERROR);
                }
                break;
            //上传报告
            case Codes.REPORT_EDIT:
                if (event.getMsg().equalsIgnoreCase(String.valueOf(TestManager.getReportID(tag)))) {
                    if (event.isSuccess()) {
                        TastyUtils.makeTextShort(R.string.string_upload_success, TastyToast.SUCCESS);
                        mUpdataTempTimer.cancel();
                        mFabReconnect.setVisibility(View.VISIBLE);
                        mFabStopTest.setVisibility(View.INVISIBLE);
                        mFabShare.setEnabled(false);
                        mFabRealChart.setEnabled(false);

                        //清除数据
                        deleteTestInfo();

                        //上传成功后跳转详细报告页
                        if (null != event.getObj()) {
                            Intent goDetial = new Intent(getActivity(), ReportDetailActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable(Extras.REPORT, (Report) event.getObj());
                            goDetial.putExtras(bundle);
                            startActivity(goDetial);
                        }
                        mTvBluetoothState.setText(R.string.string_disconnect);
                        mTvBluetoothState.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getContext(), R.mipmap.bluetooth_connecting), null, null, null);

                    } else {
                        TastyUtils.makeTextShort(getString(R.string.string_upload_fail) + event.getMsg(), TastyToast.ERROR);
                        EventBus.getDefault().post(new MainEvent(tag, Codes.BT_STOP_TEST));
                    }

                }
                break;
            //档案编辑，同步更新界面
            case Codes.NET_PRF_EDIT:
                if (event.isSuccess() && null != event.getObj()) {
                    Profile profile = (Profile) event.getObj();
                    if (profile != null && Objects.equals(profile.id, TestManager.getProfileID(tag))) {
                        TestManager.get(tag).setProfile(profile);
                        mTvProfileName.setText(profile.getRealname());
                        mSdvProfileAvatar.setImageURI(profile.getAvatar());
                    }
                }
                break;
            default:
                break;
        }
    }

    //删除界面，清除缓存
    private void deleteTestInfo() {
        ThreadUtils.runOnOtherThread(() -> {
            if (2 == isDelete) {
                boolean flag = false;
                while (!flag) {
                    if (msgCount <= 0) {
                        EventBus.getDefault().post(new MainEvent(tag, Codes.TEST_DELTE_PAGER));
                        TestManager.remove(tag);
                        flag = true;
                    }
                }
            } else {
                TestManager.get(tag).isGetRptID = false;
                RealData realData = new RealData();
                realData.setDevice(TestManager.getDevice(tag));
                realData.setProfile(TestManager.getProfile(tag));
                TestManager.put(tag, realData);
            }
        });
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (isShare) {
            return;
        }
        if (getArguments() != null) {
            tag = getArguments().getString(ARG_PARAM1);
        } else {
            TastyUtils.makeTextShort(getString(R.string.get_device_info_failed), TastyToast.ERROR);
        }

        if (mUpdataTempTimer == null) {
            mUpdataTempTimer = new UpdataTempTimer(Long.MAX_VALUE, 1000);
        }

        LogUtils.d(tag);

        tempUnit = SpUtils.getInt(Extras.TEMP_UNIT, Config.TEMP_UNIT_DEFAULT);

        mFormat = new DecimalFormat("###,###,###,###.00");

        if (mADBuilder == null) {
            mADBuilder = new AlertDialog.Builder(getActivity());
        }

        mFace = Typeface.createFromAsset(getActivity().getAssets(), "fonts/DIGITAL-7MONO.TTF");

        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setMessage(getString(R.string.string_connecting));
        mProgressDialog.setCancelable(false);
        LogUtils.e("RealTimeItemFragment onCreate" + tag);
        inityun();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_real_time_item, container, false);
        initView(view);
        if (TestManager.get(tag) != null &&
                !TestManager.get(tag).isTesting) {
            mFabReconnect.setVisibility(View.VISIBLE);
            mFabStopTest.setVisibility(View.INVISIBLE);
            mFabShare.setEnabled(false);
            mFabRealChart.setEnabled(false);
        }
        if (1 == tempUnit) {
            mTvTempUnit.setText("℃");
            mTvTempUnit1.setText("℃");
        } else if (2 == tempUnit) {
            mTvTempUnit.setText("℉");
            mTvTempUnit1.setText("℉");
        }
        if (TestManager.get(tag) != null && TestManager.get(tag).getProfile() != null) {
            mSdvProfileAvatar.setImageURI(TestManager.get(tag).getProfile().getAvatar());
            mTvProfileName.setText(TestManager.get(tag).getProfile().getRealname());
        }
        setListener();
        //  微信初始化
        api = WXAPIFactory.createWXAPI(getActivity(), Settings.WX_APP_ID, true);
        api.registerApp(Settings.WX_APP_ID);

        return view;
    }

    private void setListener() {
        mIvShowNotice.setOnClickListener(v -> {
            TestNoticeFragment testNoticeFragment = TestNoticeFragment.newInstance(null, null);
            testNoticeFragment.show(getChildFragmentManager(), "testNoticeFragment");
        });

        mIvAddNote.setOnClickListener(v -> {
            if (TestManager.get(tag).isTesting) {
                Intent addNote = new Intent(getActivity(), NotesListActivity.class);
                addNote.putExtra(Extras.REPORTID, TestManager.getReportID(tag));
                startActivity(addNote);
            }
        });

        mTvSettingWarningLow.setOnClickListener(view -> {
            initPicker();
            mLowTempPicker.show();
        });

        mTvSettingWarningHigh.setOnClickListener(view -> {
            initPicker();
            mHighTempPicker.show();
        });

        mFabRealChart.setOnClickListener(view -> {
            if (TestManager.getAllTemps(tag).size() > 1) {
                TestManager.setDrawRealLine(tag, true);
                //保存最高和最低温度
                SpUtils.saveFloat(Extras.WARNING_HIGHEST_TEMP, highWarning);
                SpUtils.saveFloat(Extras.WARNING_LOWEST_TEMP, lowWarning);
                Intent goRealChart = new Intent(getActivity(), RealTimeChartActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString(Extras.DEVICE_MAC, tag);
                goRealChart.putExtras(bundle);
                startActivity(goRealChart);
            } else {
                ToastUtils.w(R.string.have_not_data);
            }

        });

        mIvDelete.setOnClickListener(view -> {
            isDelete = 2;
            stopTestAndDeleteCardDialog();
        });

        mFabStopTest.setOnClickListener(view -> {
            isDelete = 1;
            stopTestSheetDialog();
        });

        mFabShare.setOnClickListener(view -> {
            shareDevice();
        });

        mFabReconnect.setOnClickListener(v -> {
            if (null == mProgressDialog) {
                mProgressDialog = new ProgressDialog(getActivity());
                mProgressDialog.setMessage(getString(R.string.connect_ing));
            }
            mProgressDialog.setMessage(getString(R.string.connect_ing));
            mProgressDialog.show();
            if (!TestManager.get(tag).isTesting) {
                initData();
            }
            EventBus.getDefault().post(new MainEvent(Codes.BT_RECONNECT_DEVICE, TestManager.get(tag).getDevice()));
        });
    }

    private void shareDevice() {
        if (SpUtils.getBoolean(Extras.APP_EDITION, false)) {
            shareXmpp();
            return;
        }
        final String[] stringItems = {getString(R.string.wx_share), getString(R.string.app_share)};
        final ActionSheetDialog dialog = new ActionSheetDialog(getContext(), stringItems, getActivity().getWindow().getDecorView().getRootView().findViewById(R.id.drawer_layout));
        dialog.title(getString(R.string.share));
        dialog.titleTextSize_SP(14F);
        dialog.show();
        dialog.setOnOperItemClickL((parent, view1, position, id) -> {
            switch (position) {
                case 0:
                    shareWeChat();
                    break;
                case 1:
                    shareXmpp();
                    break;

                default:
                    break;
            }
            dialog.dismiss();
        });
    }

    private void shareXmpp() {
        Intent goShare = new Intent(getActivity(), DeviceShareActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(Extras.PRF_PROFILEID, String.valueOf(TestManager.getProfileID(tag)));
        bundle.putString(Extras.DEVICE_ID, String.valueOf(TestManager.getDeviceID(tag)));
        goShare.putExtras(bundle);
        startActivityForResult(goShare, DEVICE_SHARE);
    }

    private void shareWeChat() {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = "http://www.protontek.com/vcare-api/wx/site/shareProfile?scretString=" + PrfCenter.obtainProfileID(TestManager.get(tag).getProfile());
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = "卡帕奇体温共享";
        msg.description = "我邀请你一起查看宝宝" + TestManager.get(tag).getProfile().getRealname() + "的体温";
        Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        msg.thumbData = bmpToByteArray(thumb, true);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpdf");
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;
        if (api.sendReq(req)) {
            LogUtils.d("Sucess");
        }
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    private void initData() {
        isDelete = 0;
        isNtfPower = false;
        isFirstHigh = false;
        CanHighNtf = true;
        CanLowNtf = true;
    }

    public void updataPower(int power) {
        mTvPowerValue.setText(power + "%");
        if (power >= 90) {
            mIvPower.setImageResource(R.mipmap.power_100);
        }
        if (power >= 80) {
            mIvPower.setImageResource(R.mipmap.power_90);
        } else if (power >= 70) {
            mIvPower.setImageResource(R.mipmap.power_80);
        } else if (power >= 60) {
            mIvPower.setImageResource(R.mipmap.power_70);
        } else if (power >= 50) {
            mIvPower.setImageResource(R.mipmap.power_60);
        } else if (power >= 40) {
            mIvPower.setImageResource(R.mipmap.power_50);
        } else if (power >= 30) {
            mIvPower.setImageResource(R.mipmap.power_40);
        } else if (power >= 20) {
            mIvPower.setImageResource(R.mipmap.power_30);
        } else {
            if (power >= 10) {
                mIvPower.setImageResource(R.mipmap.power_20);
            } else if (power >= 0) {
                mIvPower.setImageResource(R.mipmap.power_10);
            } else if (power <= 0) {
                mIvPower.setImageResource(R.mipmap.power_0);
            }
            if (!isNtfPower && power < 20 && getBoolean(Extras.SETTING_LOW_POWER, Config.LOW_POWER_WARNING_DEFAULT)) {
                isNtfPower = true;
                Intent intent = new Intent(VCare.get(), MainActivity.class);
                NotificationUtils.createNotif(getActivity(), getString(R.string.string_battery_low), getString(R.string.string_battery_low), getString(R.string.string_battery_less_20), intent, NtfID.LOW_POWER_WARNING);

                AlertDialog.Builder ADBuilder = new AlertDialog.Builder(getActivity());
                ADBuilder.setTitle(R.string.string_tishi);
                ADBuilder.setMessage(getString(R.string.string_battery_less_20));
                ADBuilder.setNegativeButton(R.string.string_no_longer_tip, (dialog, which) -> {
                    NotificationUtils.clearNotification(NtfID.LOW_POWER_WARNING);
                });

                AlertDialog dialog = ADBuilder.create();
                dialog.setCancelable(false);
                //在dialog  show方法之前添加如下代码，表示该dialog是一个系统的dialog**
                dialog.getWindow().setType((WindowManager.LayoutParams.TYPE_TOAST));
                dialog.show();
            }
            mIvPower.setImageResource(R.mipmap.power_0);
        }
    }

    private void initPicker() {
        if (1 == tempUnit) {
            mHighTempPicker = new NumberPicker(getActivity());
            mHighTempPicker.setRange(37.0, 42.9, 0.1);
            mHighTempPicker.setSelectedItem(FormatUtils.float2double(highWarning));
            mHighTempPicker.setLabel("℃");
            mHighTempPicker.setTitleText(R.string.config_height_temp);

            mLowTempPicker = new NumberPicker(getActivity());
            mLowTempPicker.setRange(30.0, 36.0, 0.1);
            mLowTempPicker.setSelectedItem(FormatUtils.float2double(lowWarning));
            mLowTempPicker.setLabel("℃");
            mLowTempPicker.setTitleText(R.string.config_low_temp);
        } else if (2 == tempUnit) {
            mHighTempPicker = new NumberPicker(getActivity());
            mHighTempPicker.setRange(98.6, 109.2, 0.1);
            mHighTempPicker.setSelectedItem(FormatUtils.float2double(FormatUtils.c2F(highWarning)));
            mHighTempPicker.setLabel("℉");
            mHighTempPicker.setTitleText(R.string.config_height_temp);

            mLowTempPicker = new NumberPicker(getActivity());
            mLowTempPicker.setRange(86.0, 96.6, 0.1);
            mLowTempPicker.setSelectedItem(FormatUtils.float2double(FormatUtils.c2F(lowWarning)));
            mLowTempPicker.setLabel("℉");
            mLowTempPicker.setTitleText(R.string.config_low_temp);

        }

        mLowTempPicker.setOnNumberPickListener(new NumberPicker.OnNumberPickListener() {
            @Override
            public void onNumberPicked(int index, Number item) {
                if (null != TestManager.get(tag)) {
                    TestManager.get(tag).warningLow = item.floatValue();
                }
                if (1 == tempUnit) {
                    lowWarning = item.floatValue();
                    mTvSettingWarningLow.setText(mFormat.format(item.floatValue()) + "℃");
                } else if (2 == tempUnit) {
                    lowWarning = FormatUtils.f2C(item.floatValue());
                    mTvSettingWarningLow.setText(mFormat.format(item.floatValue()) + "℉");
                }

            }
        });

        mHighTempPicker.setOnNumberPickListener(new NumberPicker.OnNumberPickListener() {
            @Override
            public void onNumberPicked(int index, Number item) {
                if (null != TestManager.get(tag)) {
                    TestManager.get(tag).warningHigh = item.floatValue();
                }
                if (1 == tempUnit) {
                    highWarning = item.floatValue();
                    mTvSettingWarningHigh.setText(item.floatValue() + "℃");
                } else if (2 == tempUnit) {
                    highWarning = FormatUtils.f2C(item.floatValue());
                    mTvSettingWarningHigh.setText(item.floatValue() + "℉");
                }

            }
        });
    }

    private void stopTestSheetDialog() {
        final String[] stringItems = {getString(R.string.string_save), getString(R.string.string_not_save)};
        final ActionSheetDialog dialog = new ActionSheetDialog(getContext(), stringItems, getActivity().getWindow().getDecorView().getRootView().findViewById(R.id.drawer_layout));
        dialog.title(getString(R.string.string_end_measure) + "?");
        dialog.titleTextSize_SP(14F);
        dialog.show();
        dialog.setOnOperItemClickL((parent, view1, position, id) -> {
            switch (position) {
                case 0:
                    sendShareMsg(XTypes.STATUS_STOP_TEST, 0f);
                    if (TestManager.get(tag).isGetRptID) {
                        if (null == TestManager.getStartTime(tag) || 30 * 1000 < System.currentTimeMillis() - TestManager.getStartTime(tag)) {
                            TestManager.upLoadTempData(tag);
                        } else {
                            TastyUtils.makeTextShort(R.string.measure_time_too_short, TastyToast.CONFUSING);
                            deleteTestInfo();
                        }
                    } else if (null == TestManager.getDeviceID(tag)) {
                        TastyUtils.makeTextShort(R.string.string_create_report_fail, TastyToast.ERROR);
                    }
                    mUpdataTempTimer.cancel();
                    mFabReconnect.setVisibility(View.VISIBLE);
                    mFabStopTest.setVisibility(View.INVISIBLE);
                    mFabShare.setEnabled(false);
                    mFabRealChart.setEnabled(false);

                    mTvRealTimeTemp.setText("--.--");
                    mTvRealtimeHighestTemp.setText("--.--");
                    mTvSumTestTime.setText(R.string.string_h_m);
                    EventBus.getDefault().post(new MainEvent(tag, Codes.BT_STOP_TEST));

                    TestManager.setTesting(tag, false);
                    mTvBluetoothState.setText(R.string.string_disconnect);
                    mTvBluetoothState.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getContext(), R.mipmap.bluetooth_connecting), null, null, null);
                    break;
                case 1:
                    sendShareMsg(XTypes.STATUS_STOP_TEST, 0f);
                    TestManager.get(tag).isTesting = false;
                    deleteTestInfo();
                    mUpdataTempTimer.cancel();
                    mFabReconnect.setVisibility(View.VISIBLE);
                    mFabStopTest.setVisibility(View.INVISIBLE);
                    mFabShare.setEnabled(false);
                    mFabRealChart.setEnabled(false);
                    mTvRealTimeTemp.setText("--.--");
                    mTvRealtimeHighestTemp.setText("--.--");
                    mTvSumTestTime.setText(R.string.string_h_m);
                    EventBus.getDefault().post(new MainEvent(tag, Codes.BT_STOP_TEST));
                    mTvBluetoothState.setText(R.string.string_disconnect);
                    mTvBluetoothState.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getContext(), R.mipmap.bluetooth_connecting), null, null, null);
                    break;
                default:
                    break;
            }
            dialog.dismiss();
        });
    }

    private void stopTestAndDeleteCardDialog() {

        if (TestManager.get(tag).isTesting) {
            final String[] stringItems = {getString(R.string.string_end_measure)};
            final ActionSheetDialog dialog = new ActionSheetDialog(getContext(), stringItems, getActivity().getWindow().getDecorView().getRootView().findViewById(R.id.drawer_layout));
            dialog.title(getString(R.string.string_end_measure_2));
            dialog.titleTextSize_SP(14F);
            dialog.show();
            dialog.setOnOperItemClickL((parent, view1, position, id) -> {
                switch (position) {
                    case 0:
                        stopTestSheetDialog();
                        break;
                    default:
                        break;
                }
                dialog.dismiss();
            });
        } else {
            final String[] stringItems = {getString(R.string.string_close)};
            final ActionSheetDialog dialog = new ActionSheetDialog(getContext(), stringItems, getActivity().getWindow().getDecorView().getRootView().findViewById(R.id.drawer_layout));
            dialog.isTitleShow(false).show();
            dialog.setOnOperItemClickL((parent, view1, position, id) -> {
                switch (position) {
                    case 0:
                        if (!TestManager.get(tag).isTesting && 2 == isDelete) {
                            EventBus.getDefault().post(new MainEvent(tag, Codes.TEST_DELTE_PAGER));
                        }
                        break;
                    default:
                        break;
                }
                dialog.dismiss();
            });
        }
    }

    @Override
    public void onEventMainThread(MainEvent event) {
        dealOnEvent(event);
    }

    private void sendShareMsg(int type, float temp) {
        try {
            if (!TestManager.get(tag).isGetRptID) {
                return;
            }
            msgCount += 1;
            ThreadUtils.postMsg(() -> {
                try {
                    XmppMsg tempXmpp = new XmppMsg();
                    if (null == TestManager.getReportID(tag) || null == TestManager.getShareList(tag)) {
                        msgCount -= 1;
                        return;
                    }

                    Profile profile = TestManager.get(tag).getProfile();
                    if (profile != null) {
                        tempXmpp.displayAvatar = profile.getAvatar();
                        tempXmpp.setDisplayName(profile.getRealname());
                    }
                    tempXmpp.setDisplayMax(TestManager.getHighestTemp(tag));
                    tempXmpp.setDeviceMac(tag);
                    tempXmpp.setDisplayCurrent(temp);
                    tempXmpp.setNow(System.currentTimeMillis());
                    if (TestManager.getReportID(tag) != null) {
                        tempXmpp.setReportId(TestManager.getReportID(tag));
                    }
                    tempXmpp.setDisplayStatus(type);
                    tempXmpp.setUid(VCare.get().getUid());

                    if (TestManager.getShareList(tag) != null) {
                        for (ShareHistory.SharelistBean sb :
                                TestManager.getShareList(tag)) {
                            if (sb.isCanSend()) {
                                LogUtils.d(sb);
                                LogUtils.d(tempXmpp);
                                XMPPCenter.sendMsgCustom(tempXmpp, sb.getUid());
                            }
                        }
                    }

                    msgCount -= 1;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendUNShareMsg(long uid) {
        //  防止无数据时，产生数组越界
        if (!TestManager.get(tag).isGetRptID) {
            return;
        }
        XmppMsg tempXmpp = new XmppMsg();
        tempXmpp.setNow(System.currentTimeMillis());
        tempXmpp.setToUid(uid);
        tempXmpp.setDeviceMac(tag);
        tempXmpp.setReportId(TestManager.getReportID(tag));
        tempXmpp.setDisplayStatus(XTypes.STATUS_UNSHARE);
        tempXmpp.setDisplayName(TestManager.get(tag).getProfile().getRealname());
        tempXmpp.setUid(VCare.get().getUid());
        LogUtils.e(tempXmpp);
        XMPPCenter.sendMsg(tempXmpp, uid);
    }

    private void initView(View view) {
        mTvDeviceId = view.findViewById(R.id.tv_device_id);
        mIvPower = view.findViewById(R.id.iv_power);
        mTvPowerValue = view.findViewById(R.id.tv_power_value);
        mLnlRangeNotice = view.findViewById(R.id.lnl_range_notice);
        mIvShowNotice = view.findViewById(R.id.iv_show_notice);
        mTvBluetoothState = view.findViewById(R.id.tv_bluetooth_state);
        mIvAddNote = view.findViewById(R.id.iv_add_note);
        mTvTempRange = view.findViewById(R.id.tv_temp_range);
        mSdvProfileAvatar = view.findViewById(R.id.sdv_profile_avatar);
        mTvProfileName = view.findViewById(R.id.tv_profile_name);
        mTvRealTimeTemp = view.findViewById(R.id.tv_real_time_temp);
        mTvTempUnit = view.findViewById(R.id.tv_temp_unit);
        mIvDelete = view.findViewById(R.id.iv_delete);
        mTvRealtimeHighestTemp = view.findViewById(R.id.tv_realtime_highest_temp);
        mTvTempUnit1 = view.findViewById(R.id.tv_temp_unit1);
        mTvSumTestTime = view.findViewById(R.id.tv_sum_test_time);
        mTvSettingWarningLow = view.findViewById(R.id.tv_setting_warning_low);
        mTvSettingWarningHigh = view.findViewById(R.id.tv_setting_warning_high);
        mFabRealChart = view.findViewById(R.id.fab_add_note);
        mFabStopTest = view.findViewById(R.id.fab_stop_test);
        mFabShare = view.findViewById(R.id.fab_share);
        if (VCare.isInternal) {
            mFabShare.setVisibility(View.GONE);
        }
        mRtlRealTimeTemp = view.findViewById(R.id.rtl_real_time_temp);
        mFabReconnect = view.findViewById(R.id.fab_reconnect);
        //数据填充
        if (TestManager.get(tag) != null && TestManager.get(tag).getProfile() != null) {
            mSdvProfileAvatar.setImageURI(TestManager.get(tag).getProfile().getAvatar());
            mTvProfileName.setText(TestManager.get(tag).getProfile().getRealname());
        }
        mTvSettingWarningHigh.setText(mFormat.format(highWarning));
        mTvSettingWarningLow.setText(mFormat.format(lowWarning));
        mTvRealTimeTemp.setTypeface(mFace);
        mFabShare.setBackgroundTintList(ContextCompat.getColorStateList(getContext(), R.color.share_fad));
        mFabRealChart.setBackgroundTintList(ContextCompat.getColorStateList(getContext(), R.color.real_time_fad));
    }


    // TODO: 2016/12/15 存在内存泄漏 ，待解决（show or clea方法）

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (1 == tempUnit) {
                mTvSettingWarningHigh.setText(highWarning + "℃");
                mTvSettingWarningLow.setText(lowWarning + "℃");
            } else if (2 == tempUnit) {
                mTvSettingWarningHigh.setText(FormatUtils.c2FHalfDown(highWarning) + "℉");
                mTvSettingWarningLow.setText(FormatUtils.c2FHalfDown(lowWarning) + "℉");
            }
        }
    }

    /**
     * @param type 1高烧 2低烧
     */
    private void showNotification(int type) {

        try {
            if (null == getActivity() || getActivity().isDestroyed()) {
                return;
            }

            if (isHightNtfShow) {
                return;
            }

            isHightNtfShow = true;

            if (!CanLowNtf && !CanHighNtf) return;

            Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
            Intent intent = new Intent(getActivity(), MainActivity.class);
            if (type == 1) {
                MsgCenter.maxTempPush(TestManager.getProfileID(tag), TestManager.getRealTemp(tag));
                NotificationUtils.createNotif(VCare.get(), VCare.get().getString(R.string.child_have_fever),
                        VCare.get().getString(R.string.hava_height_fever),
                        VCare.get().getString(R.string.temp_too_height),
                        intent, NtfID.LOW_OR_HIGH_WARNING);
            } else {
                NotificationUtils.createNotif(getActivity(), VCare.get().getString(R.string.child_have_low_fever),
                        VCare.get().getString(R.string.heave_low_fever),
                        VCare.get().getString(R.string.temp_too_low),
                        intent, NtfID.LOW_OR_HIGH_WARNING);
            }

            long pattern[] = {50, 50, 50, 50, 50, 50, 50, 50};
            if (vibrator != null) {
                vibrator.vibrate(pattern, 5);
            }

            SweetAlertDialog dialog = new SweetAlertDialog(getActivity(), Type.NORMAL_TYPE);
            if (1 == type) {
                dialog.setTitleText(getString(R.string.high_temp_notice));
                dialog.setContentText(TestManager.getProfile(tag).getRealname() + VCare.get().getString(R.string.temp_to_height) + "\n\n" + getString(R.string.device_name_) + TestManager.getDevice(tag).getName());
            } else {
                dialog.setTitleText(getString(R.string.low_temp_notice));
                dialog.setContentText(TestManager.getProfile(tag).getRealname() + VCare.get().getString(R.string.temp_is_too_low) + "\n\n" + getString(R.string.device_name_) + TestManager.getDevice(tag).getName());
            }

            dialog.setCancelable(false);
            dialog.showCancelButton(true);
            dialog.setConfirmText(FormatUtils.formatTime(TestManager.getAlarmInterval()) + getString(R.string.butixiang));
            dialog.setCancelText(getString(R.string.known));
            dialog.setCancelClickListener(sweetAlertDialog -> {
                NotificationUtils.clearNotification(NtfID.LOW_OR_HIGH_WARNING);
                if (1 == type) {
                    CanHighNtf = false;
                } else {
                    CanLowNtf = false;
                }
                isHightNtfShow = false;
                vibrator.cancel();
                dialog.dismiss();
            });
            dialog.setConfirmClickListener(sweetAlertDialog -> {
                clearNotification(LOW_OR_HIGH_WARNING);
                Runnable runnable = () -> {
                    if (1 == type) {
                        highNtfTime = System.currentTimeMillis();
                        for (int i = 0; i <= TestManager.getAlarmInterval() / 1000 && !CanHighNtf && TestManager.isTesting(tag); i++) {
                            SystemClock.sleep(1000);
                        }
                        CanHighNtf = true;
                    } else {
                        lowNtfTime = System.currentTimeMillis();

                        for (int i = 0; i <= TestManager.getAlarmInterval() / 1000 && !CanLowNtf && TestManager.isTesting(tag); i++) {
                            SystemClock.sleep(1000);
                        }
                        CanLowNtf = true;
                    }
                };
                isHightNtfShow = false;
                vibrator.cancel();
                ThreadUtils.runOnOtherThread(runnable);
                dialog.dismiss();
            });
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //删除通知
    private void clearNotification(int ntfCode) {
        // 启动后删除之前我们定义的通知
        NotificationManager notificationManager = (NotificationManager)
                VCare.get().getSystemService(NOTIFICATION_SERVICE);
        notificationManager.cancel(ntfCode);
    }

    private void inityun() {
        if (!com.proton.carepatchtemp.constant.Settings.enableShare) {
            return;
        }
        XMPPCenter.loginChat();
        VCare.get().need = false;
    }

    private class UpdataTempTimer extends MyCountDownTimer {

        private int reconnectTime = 0;

        public UpdataTempTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long l) {

            try {
                if (null != TestManager.getRealTemp(tag)) {

                    if (TestManager.getHighestTemp(tag) > 36.0) {
                        isFirstHigh = true;
                    }

                    if (isFirstHigh) {
                        if (null != TestManager.getRealTemp(tag) && TestManager.getRealTemp(tag) >= highWarning) {
                            mRtlRealTimeTemp.setBackground(ContextCompat.getDrawable(VCare.get(), R.drawable.realtime_temp_bg_red));
                            //高温报警开关是否开启
                            if (TestManager.isHighAlarmOpen()) {

                                //先判断是否点击一定时间内不再报警
                                long highAlarmDiv = System.currentTimeMillis() - highNtfTime;
                                if (highAlarmDiv >= TestManager.getAlarmInterval()) {

                                    //满足后判断是否是由低温变成高温
//                                    int size = TestManager.getAfterTemps(tag).size();
//                                    if (size > 2 && TestManager.getRealTemp(tag) >= highWarning && TestManager.getAfterTemps(tag).get(size - 2) < highWarning) {
//                                        CanHighNtf = true;
//                                    }
//
//                                    //判断是否可以报警
                                    if (CanHighNtf) {
                                        showNotification(1);
                                    }
                                }
                            }
                        } else if (null != TestManager.getRealTemp(tag) && TestManager.getRealTemp(tag) <= lowWarning) {
                            mRtlRealTimeTemp.setBackground(ContextCompat.getDrawable(VCare.get(), R.drawable.realtime_temp_bg_blue_low));
                            //低温报警开关是否开启
                            if (TestManager.isLowAlarmOpen()) {

                                //判断是否满足时间间隔
                                long lowAlramDiv = System.currentTimeMillis() - lowNtfTime;
                                if (lowAlramDiv >= TestManager.getAlarmInterval()) {

                                    //满足后判断是否是由高温变成低温
//                                    int size = TestManager.getAfterTemps(tag).size();
//                                    if (size > 2 && TestManager.getRealTemp(tag) <= lowWarning && TestManager.getAfterTemps(tag).get(size - 2) > lowWarning) {
//                                        CanLowNtf = true;
//                                    }

                                    if (CanLowNtf) {
                                        showNotification(2);
                                    }
                                }
                            }
                        } else {
                            mRtlRealTimeTemp.setBackground(ContextCompat.getDrawable(VCare.get(), R.drawable.realtime_temp_bg_blue));
                        }

                    } else {
                        mRtlRealTimeTemp.setBackground(ContextCompat.getDrawable(VCare.get(), R.drawable.realtime_temp_bg_blue));
                    }

                    mTvDeviceId.setText(tag);
                    //更新最高温度和实时温度

                    if (1 == tempUnit) {
                        if (TestManager.getHighestTemp(tag) < 25) {
                            mTvRealtimeHighestTemp.setText("< 25.00");
                        } else if (TestManager.getHighestTemp(tag) > 45) {
                            mTvRealtimeHighestTemp.setText("> 45.00");
                        } else {
                            mTvRealtimeHighestTemp.setText(mFormat.format(TestManager.getHighestTemp(tag)));
                        }
                        if (null != TestManager.getRealTemp(tag)) {
                            mTvRealTimeTemp.setText(mFormat.format((double) TestManager.getRealTemp(tag)));
                        }
                    } else if (2 == tempUnit) {
                        if (TestManager.getHighestTemp(tag) < 25) {
                            mTvRealtimeHighestTemp.setText("< 77");
                        } else if (TestManager.getHighestTemp(tag) > 45) {
                            mTvRealtimeHighestTemp.setText("> 113");
                        } else {
                            mTvRealtimeHighestTemp.setText(mFormat.format(FormatUtils.c2F(TestManager.getHighestTemp(tag))));
                        }
                        if (null != TestManager.getRealTemp(tag)) {
                            mTvRealTimeTemp.setText(mFormat.format((double) FormatUtils.c2F(TestManager.getRealTemp(tag))));
                        }
                    }

                    //不在有效范围内不显示
                    if (NumUtils.withinTempRange(TestManager.getRealTemp(tag))) {
                        mLnlRangeNotice.setVisibility(View.INVISIBLE);
                    } else {
                        mLnlRangeNotice.setVisibility(View.VISIBLE);
                        mTvRealTimeTemp.setText("--.--");
                    }

                    isDisconnectWarm = false;
                    timeOut = 0;
                } else {
                    timeOut += 1000;
                }

                if (timeOut >= Settings.TEMP_LOAD_TIME_OUT) {
                    mTvRealTimeTemp.setText("--.--");
                    mTvRealtimeHighestTemp.setText("--.--");
                    mTvSumTestTime.setText(getString(R.string.string_h_m));
                    if (!isDisconnectWarm) {
                        isDisconnectWarm = true;
                        if (getBoolean(Extras.SETTING_DEVICE_DISC_WARNING, Config.DEVICE_DISCONNECT_WARNING_DEFAULT)) {
                            Intent intent = new Intent(VCare.get(), MainActivity.class);
                            NotificationUtils.createNotif(getActivity(), getString(R.string.string_device_disconnect), getString(R.string.string_device_disconnect), getString(R.string.string_device_disconnect_and_retry), intent, DEVICE_DISCONNECTED);
                            SweetAlertDialog mydialog = new SweetAlertDialog(getContext(), Type.NORMAL_TYPE);
                            mydialog.setCancelable(false);
                            mydialog.setTitleText(getString(R.string.string_tips));
                            mydialog.setContentText(getString(R.string.string_device_disconnect_and_check));
                            mydialog.showCancelButton(true);
                            mydialog.setConfirmText(getString(R.string.string_i_know));
                            mydialog.setConfirmClickListener(sweetAlertDialog -> {
                                mydialog.dismiss();
                                NotificationUtils.clearNotification(NtfID.DEVICE_DISCONNECTED);
                            });
                            mydialog.show();
                        }

                        mFabReconnect.setVisibility(View.VISIBLE);
                        mFabStopTest.setVisibility(View.INVISIBLE);
                    }
                }


                if (1 == tempUnit) {
                    mTvSettingWarningHigh.setText(mFormat.format(highWarning) + "℃");
                    mTvSettingWarningLow.setText(mFormat.format(lowWarning) + "℃");
                    mTvTempRange.setText("(25℃~45℃)");
                } else if (2 == tempUnit) {
                    mTvSettingWarningHigh.setText(mFormat.format(FormatUtils.c2FHalfDown(highWarning)) + "℉");
                    mTvSettingWarningLow.setText(mFormat.format(FormatUtils.c2FHalfDown(lowWarning)) + "℉");
                    mTvTempRange.setText("(77℉~113℉)");
                }
                if (null != TestManager.getStartTime(tag) && timeOut < Settings.TEMP_LOAD_TIME_OUT) {
                    mTvSumTestTime.setText(FormatUtils.longToHMS(System.currentTimeMillis() - TestManager.get(tag).startTime));
                }

                if (timeOut >= Settings.TEMP_LOAD_TIME_OUT && TestManager.get(tag) != null && TestManager.get(tag).isTesting && !isConnected) {
                    reconnectTime += 1;
                    if (reconnectTime % 10 == 0) {
                        //断开重连 10秒发送一次
                        EventBus.getDefault().post(new MainEvent(Codes.BT_RECONNECT, TestManager.get(tag).getDevice()));
                    }
                    mTvBluetoothState.setText(R.string.string_connecting);
                    mTvBluetoothState.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getContext(), R.mipmap.bluetooth_connecting), null, null, null);
                } else {
                    reconnectTime = 0;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFinish() {
            this.start();
        }

    }
}
